package org.jeecg.modules.demo.users.service.impl;

import org.jeecg.modules.demo.users.entity.Users;
import org.jeecg.modules.demo.users.entity.Address;
import org.jeecg.modules.demo.users.mapper.AddressMapper;
import org.jeecg.modules.demo.users.mapper.UsersMapper;
import org.jeecg.modules.demo.users.service.IUsersService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.util.List;
import java.util.Collection;

/**
 * @Description: users
 * @Author: jeecg-boot
 * @Date:   2024-07-05
 * @Version: V1.0
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private AddressMapper addressMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveMain(Users users, List<Address> addressList) {
		usersMapper.insert(users);
		if(addressList!=null && addressList.size()>0) {
			for(Address entity:addressList) {
				//外键设置
				entity.setUserId(users.getId());
				addressMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(Users users,List<Address> addressList) {
		usersMapper.updateById(users);
		
		//1.先删除子表数据
		addressMapper.deleteByMainId(users.getId());
		
		//2.子表数据重新插入
		if(addressList!=null && addressList.size()>0) {
			for(Address entity:addressList) {
				//外键设置
				entity.setUserId(users.getId());
				addressMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		addressMapper.deleteByMainId(id);
		usersMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			addressMapper.deleteByMainId(id.toString());
			usersMapper.deleteById(id);
		}
	}
	
}
